<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-02-14 19:58:55
 * @Description  : 添加或者更新通知面板
-->

<template>
  <div class="bg-lightColor notice-edit-con p-3 text-[13px]">
    <n-grid x-gap="12" :cols="1" class="mb-2">
      <n-gi>
        <n-button
          type="primary"
          size="small"
          class="!text-[13px]"
          @click="backView"
        >
          <div class="mr-2 rotate-90 transform">
            <SvgIcon icon="xiala" color="#fff" size="10px"></SvgIcon>
          </div>
          返回
        </n-button>
      </n-gi>
    </n-grid>
    <n-divider class="!my-2" />
    <n-form
      ref="noticeFormRef"
      :label-width="isSmall ? 100 : 120"
      label-placement="left"
      :label-align="isSmall ? 'left' : 'right'"
      :model="notice"
      size="small"
      :rules="formRule"
      require-mark-placement="left"
    >
      <n-form-item label="消息标题：" path="name">
        <n-input
          v-model:value="notice.name"
          :allow-input="noSideSpace"
          placeholder="请输入消息标题"
          clearable
          :maxlength="25"
        />
      </n-form-item>
      <n-form-item label="消息内容：" path="content">
        <n-input
          type="textarea"
          v-model:value="notice.content"
          placeholder="请输入消息内容："
          :allow-input="noSideSpace"
          clearable
        />
      </n-form-item>
      <n-form-item label="推送对象：" path="auth">
        <WpCheckGroup
          :options="authOptions"
          v-model:value="authType"
        ></WpCheckGroup>
        <div class="ml-[12px] text-gray-400 text-[12px]">
          选择推送给所有人，或推送给指定用户、用户组、权限组
        </div>
      </n-form-item>

      <MyTransition>
        <div v-if="authType.includes(1)">
          <n-form-item class="!w-[400px]" label="选择用户：">
            <UserSelect
              @change-value="handleUserChange"
              :default-user-ids="notice.auth.userIds"
            ></UserSelect>
          </n-form-item>
        </div>
      </MyTransition>

      <MyTransition>
        <div v-if="authType.includes(2)">
          <n-form-item class="!w-[400px]" label="选择部门：">
            <DepSelect
              @change-value="handleDepChange"
              :default-dep-ids="notice.auth.depIds"
            ></DepSelect>
          </n-form-item>
        </div>
      </MyTransition>

      <MyTransition>
        <div v-if="authType.includes(3)">
          <n-form-item class="!w-[400px]" label="选择角色：">
            <RoleSelect
              :role-type="0"
              class-name="!w-[400px]"
              @change-value="handleRoleChange"
              :default-role-ids="notice.auth.roleIds"
            ></RoleSelect>
          </n-form-item>
        </div>
      </MyTransition>

      <n-form-item label="推送方式：" path="type">
        <n-radio-group v-model:value="notice.type" name="radiobuttongroup2">
          <n-radio-button :value="0" label="立即推送" />
          <n-radio-button :value="1" label="计划推送" />
        </n-radio-group>
      </n-form-item>

      <MyTransition>
        <div v-if="notice.type === 1">
          <n-form-item label="推送时间：" path="sendTime">
            <n-date-picker
              v-model:formatted-value="notice.sendTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              clearable
            />
          </n-form-item>
        </div>
      </MyTransition>

      <n-form-item label="提示级别：" path="level">
        <n-radio-group v-model:value="notice.level" name="radiogroup3">
          <n-space>
            <n-radio :value="0"> 弱提示 </n-radio>
            <n-radio :value="1"> 强提示 </n-radio>
          </n-space>
        </n-radio-group>
      </n-form-item>

      <n-form-item label="是否启用：" path="isActive">
        <n-switch
          v-model:value="notice.isActive"
          :checked-value="1"
          :unchecked-value="0"
        />
      </n-form-item>
      <n-form-item label=" " v-permission="[PERMISSIONS.ADMIN_SETTING]">
        <n-button
          type="primary"
          class="grent-btn w-[120px]"
          @click="handleAddAndUpdateNotice"
        >
          保存
        </n-button>
      </n-form-item>
    </n-form>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import type { NoticeRes, NoticeUpdateReq } from '@/types/notice'
import { PERMISSIONS } from '@/constants/permission'
import { noSideSpace } from '@/utils'
import { userMenuShow } from '@/hooks/useMenuShow'
import WpCheckGroup from './WpCheckGroup.vue'

const { isSmall } = userMenuShow()

const props = defineProps<{
  isModify: boolean
  noticeRes?: NoticeRes
}>()

const authOptions = [
  { label: '所有人', value: 0, icon: 'a-ziyuan4' },
  { label: '指定用户', value: 1, icon: 'tianjiatianjiayonghu11' },
  { label: '指定部门', value: 2, icon: 'yonghuwenjianjia' },
  { label: '指定角色', value: 3, icon: 'kaisuo' }
]

const emits = defineEmits<{
  (e: 'backView'): void
  (e: 'changeNotice', type: number, data: NoticeUpdateReq): void
}>()
const backView = () => {
  emits('backView')
}

const notice = reactive<NoticeUpdateReq>({
  name: '',
  content: '',
  type: 0,
  sendTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  isActive: 1,
  level: 0,
  auth: {
    all: 1,
    depIds: [],
    userIds: [],
    roleIds: []
  }
})

const initNotice = () => {
  if (props.isModify) {
    const { name, content, type, sendTime, isActive, level, auth, id } =
      props.noticeRes as NoticeRes

    const parseAuth = JSON.parse(auth)
    if (+parseAuth.all === 1) {
      authType.value = [0]
    } else {
      authType.value = []
      if (+parseAuth.depIds.length) {
        authType.value.push(2)
      }

      if (+parseAuth.roleIds.length) {
        authType.value.push(3)
      }

      if (+parseAuth.userIds.length) {
        authType.value.push(1)
      }

      if (!authType.value.length) {
        authType.value = [0]
      }
    }
    notice.noticeId = id
    notice.name = name
    notice.content = content
    notice.type = type
    notice.sendTime = dayjs(sendTime).format('YYYY-MM-DD HH:mm:ss')
    notice.isActive = isActive
    notice.level = level
    notice.auth = JSON.parse(auth)
  }
}

onMounted(() => {
  initNotice()
})

const formRule = {
  name: [
    {
      required: true,
      message: '请输入通知名称',
      trigger: ['blur']
    }
  ],
  content: [
    {
      required: true,
      message: '请输入通知内容',
      trigger: ['blur']
    }
  ]
}

const authType = ref([0])

const handleAddAndUpdateNotice = () => {
  // 验证是否有问题
  if (authType.value.includes(0)) {
    notice.auth = {
      all: 1,
      depIds: [],
      roleIds: [],
      userIds: []
    }
  } else {
    notice.auth.all = 0
    // notice.auth.userIds = notice.auth.userIds.map((item) => {
    //   const res = item.split(COMMON_SEPARATOR)
    //   return res[res.length - 1]
    // })
  }

  if (notice.type === 0) {
    notice.sendTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  }

  if (props.isModify) {
    emits('changeNotice', 1, notice)
  } else {
    emits('changeNotice', 0, notice)
  }
}

const handleRoleChange = (value: string[] | string) => {
  notice.auth.roleIds = value as string[]
}

const handleDepChange = (value: string[] | string) => {
  notice.auth.depIds = value as string[]
}

const handleUserChange = (value: string[] | string) => {
  notice.auth.userIds = value as string[]
}
</script>

<style scoped lang="scss"></style>
